/*
 * @Author: your name
 * @Date: 2020-02-22 11:52:51
 * @LastEditTime: 2020-02-24 19:49:51
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /dy/src/utils/index.ts
 */

import md5 from "blueimp-md5";
import router from "@/router";
import axios from "axios";
/**
 * 设置页面标题
 * @param title
 */
export function setPageTitle(title: string) {
  document.title = title;
}
export function toLogin() {
  removeToken()
  removeTimeDate()

  router.push('/')
}

export function getToken() {
  return localStorage.getItem("token") || "";
}
export function setToken(token: string) {
  localStorage.setItem("token", token);
}

export function removeToken() {
  return localStorage.removeItem("token");
}

export function setTimeDate(timeout: string) {
  localStorage.setItem('timeout',timeout)
}
export function getTimeDate() {
  return localStorage.getItem('timeout') || 0
}
export function removeTimeDate() {
  return localStorage.removeItem('timeout')
}
/** 加载js文件 */
export function loadJS(src: string) {
  if (
    !(Array.from(document.querySelectorAll("body script")) as Array<
      HTMLScriptElement
    >).some((script: HTMLScriptElement) => script.src.indexOf(src) >= 0)
  )
    return new Promise((resolve, reject) => {
      var script = document.createElement("script");
      script.type = "text/javascript";
      script.onload = resolve;
      script.src = src;
      document.body.appendChild(script);
    });
}

/** 加载高德地图 */
export async function loadAMap() {
  if (!window.AMap) {
    await loadJS(
      'https://webapi.amap.com/maps?v=1.4.15&key=3fb4de7e3e9ad59cc88520f3440e7515'
      );
    }
  }
  // "//webapi.amap.com/maps?v=1.4.0&key=3fb4de7e3e9ad59cc88520f3440e7515&plugin=AMap.PlaceSearch"



/** 又拍云配置 */
export const upyunConfig = {
  api: "//v0.api.upyun.com/",
  bucket: "product-jihe",
  apiSecret: "2Wjr72+Ka8To5/1WMuLb9BngCPA=",
  domain: "//img2019.jiheapp.com"
};



/** 又拍云上传 */
export async function uploadToUpyun(file: File, dirName = "img") {
  if (!file) return;

  const saveKey = `/${dirName}/{year}{mon}{day}/{filemd5}{.suffix}`;
  const url = upyunConfig.api + upyunConfig.bucket;

  let options = {
    bucket: upyunConfig.bucket,
    "save-key": saveKey,
    expiration: Math.floor(new Date().getTime() / 1000) + 86400
  };

  const policy = window.btoa(JSON.stringify(options));
  const signature = md5(policy + "&" + upyunConfig.apiSecret);

  const data = new FormData();
  data.append("policy", policy);
  data.append("signature", signature);
  data.append("file", file);

  const { data: info } = await axios({
    url,
    data,
    method: "post"
  });

  return info;
}

/**
 * 格式化又拍云给的文件路径
 * @param url 默认文件路径
 * @param mode full: 带协议的完整路径 proxy: 走反向代理的路径 auto(默认): 自适应协议头的路径
 */
export function formatUpyunUrl(
  url: string,
  mode: "full" | "proxy" | "auto" = "auto"
) {
  if (mode === "full") {
    return `https:${upyunConfig.domain}${url}`;
  } else if (mode === "proxy") {
    return `/res${url}`;
  } else {
    return `${upyunConfig.domain}${url}`;
  }
}


//时间戳转化成时间
export function transformTime(timestamp = +new Date()) {
  if (timestamp) {
      var time = new Date(timestamp);
      console.log(time,'time');
      
      var y = time.getFullYear(); //getFullYear方法以四位数字返回年份
      var M = time.getMonth() + 1; // getMonth方法从 Date 对象返回月份 (0 ~ 11)，返回结果需要手动加一
      var d = time.getDate(); // getDate方法从 Date 对象返回一个月中的某一天 (1 ~ 31)
      var h = time.getHours(); // getHours方法返回 Date 对象的小时 (0 ~ 23)
      var m = time.getMinutes(); // getMinutes方法返回 Date 对象的分钟 (0 ~ 59)
      var s = time.getSeconds(); // getSeconds方法返回 Date 对象的秒数 (0 ~ 59)
      return y + '-' + M + '-' + d + ' ' + h + ':' + m + ':' + s;
    } else {
        return '';
    }
}

